//创建audio控件
const innerAudioContext = wx.createInnerAudioContext();
const util = require('../../utils/util.js');
var user = require('../../services/user.js');
const Toast = require('../../utils/toast.js');

Page({
  data: {
    showTan: true, //弹窗
    showMessage: false, //评论
    showMenu: false, //切换菜单
    showMask: false, //遮罩层
    commentShow: false,
    showComment: '1', //评论赞赏弹窗切换
    value: 0,
    percent: 0,
    max: 401,
    pass_time: '00:00',
    total_time: '06:41',
    pause: '暂停',
    pause_disable: true,
    audioInfo: true,
    recordtype: 0,
    tabIndex: 0,
    lesson_res: [],
    sendmessagetext: '',
    lessoninfo: {},
    commentlist: [], //弹幕信息列表
    isAndroid: false,
    andoridInput: false,
    floorstatus: false,
    lessonid: 0,
    audiolist: [],
    andoridHeight:0,
    showPublish:false
  },
  //***页面加载执行***
  onLoad: function(e) {
    let that = this;
    this.setData({
      lessonid: e.id
    })
    wx.getSystemInfo({
      success: function(res) {
        if (!res.system.indexOf('Android')) {
          that.setData({
            isAndroid: true
          })
        }
      }
    })
    this.getstudylessoninfo(e) //获取初始化课程信息
    this.creatsocket(e); //creat socket
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        if (!res.system.indexOf('Android')) {
          that.setData({
            isAndroid: true
          })
        }
      }
    })
  },
  //***页面卸载执行***
  onUnload: function() {
    wx.closeSocket()
  },
  //***创建scoket连接***
  creatsocket: function(e) {
    var that = this;
    wx.connectSocket({
      url: util.socketurl,
    })
    wx.onSocketOpen(function(res) {
      console.log('WebSocket连接已打开！')
      that.setData({ //设置连接状态
        socketopen: true
      })
      var userInfo = wx.getStorageSync('userInfo');
      var data = {
        type: 'addUser',
        broadcast: 1, //加入广播 ==》1：进行房间广播， 0：不进行房间广播  
        closebroadcast: 1, //退出广播 ==》1:进行房间广播， 0:不进行房间广播   
        roomName: 'minichat_' + e.id,
        userId: userInfo.id,
        userName: userInfo.nickname,
        headUrl: userInfo.headurl,
        sendUser: userInfo,
      }
      wx.sendSocketMessage({
        data: JSON.stringify(data)
      })
    })
    wx.onSocketMessage(function(res) { //监听socket收到消息
      that.socketMessage(res.data);
    })
    wx.onSocketClose(function(res) { //监听socket断开连接
      that.setData({
        socketopen: false
      })
      //that.creatsocket(e);
    })
  },
  //***获取当前课程信息***
  getstudylessoninfo(e) {
    let that = this;
    util.request('school/getlivestudylessoninfo', {
      lesson_id: e.id
    }, 'GET').then(function(res) {
      console.log(res.data);
      if (res.errno === 0) {
        res.data.lesson_res.forEach(item => {
          if (item.res_type === 1) {
            item.bl = false;
            item.new = true;
          }
        })
        that.setData({
          lessoninfo: res.data.lessoninfo,
          lesson_res: res.data.lesson_res,
        });
        that.autoplayvoice(res.data.lesson_res)
      }
    });
  },
  //***改变评论输入框的数据***
  sendmessagetext: function(e) {
    this.setData({
      sendmessagetext: e.detail.value
    })
  },
  //***格式化socket收到的数据***
  socketMessage: function(message) {
    console.log(message);
    var messageInfo = JSON.parse(message);
    var that = this;
    if (messageInfo.sendMessage.type == 'lesson_res') { //如果是课程资源消息
      var data = {
        id: 0,
        res_type: messageInfo.sendMessage.res_type,
        teacher_name: messageInfo.sendUser.nickname,
        teacher_headurl: messageInfo.sendUser.headurl,
        res_path: messageInfo.sendMessage.res_path,
        size: messageInfo.sendMessage.size,
        addtime: messageInfo.sendMessage.addtime,
      }
      var lesson_res = this.data.lesson_res;
      lesson_res.push(data);
      console.log(lesson_res);
      lesson_res.forEach(item => {
        if (item.res_type === 1) {
          item.bl = false;
          item.new = true;
        }
      })
      that.setData({
        lesson_res: lesson_res
      })
      //that.goBottom()
    }
    if (messageInfo.sendMessage.type == 'addUser') { //如果是进入房间消息
      var commentlist = that.data.commentlist;
      commentlist.unshift({
        userid: messageInfo.sendUser.id,
        nickname: messageInfo.sendUser.nickname,
        headurl: messageInfo.sendUser.headurl,
        msg: messageInfo.sendUser.nickname + '进入了课程！',
        typeInfo:'addUser'
      })
      that.setData({
        commentlist: commentlist,
        roomNumber: messageInfo.sendMessage.roomNumber
      })
    }
    if (messageInfo.sendMessage.type == 'lesson_comment') { //如果是发布的评论信息
      var commentlist = that.data.commentlist;
      commentlist.unshift({
        userid: messageInfo.sendUser.id,
        nickname: messageInfo.sendUser.nickname,
        headurl: messageInfo.sendUser.headurl,
        msg: messageInfo.sendMessage.msg,
        typeInfo: 'lesson_comment'
      })
      that.setData({
        commentlist: commentlist,
      })
    }
    console.log(that.data.commentlist)
  },
  //**发布评论 */
  socketsendmessage: function() {
    //console.log(this.data.sendmessagetext);
    if (!this.data.sendmessagetext){
      Toast('发表内容不能为空！','noicon');
      return;
    }
    var that = this;
    var userInfo = wx.getStorageSync('userInfo'); //发送soket消息
    var addtimestamp = Math.round(Date.now() / 1000);
    var data = {
      type: 'groupSend',
      roomName: 'minichat_' + that.data.lessoninfo.lesson_id,
      sendUser: userInfo,
      sendMessage: {
        type: 'lesson_comment',
        msg: this.data.sendmessagetext,
        addtime: addtimestamp
      }
    }
    this.setData({
      sendmessagetext: '',
      showPublish:false
    })
    wx.sendSocketMessage({ //发送soket消息
      data: JSON.stringify(data)
    })
  },
  //自动循环播放
  autoplayvoice(data){
    let newData =  data.filter(item => {
       return item.res_type === 1
    })
  },
  //音频播放  
  playAudio: function(e) {
    let that = this;
    let src = e.currentTarget.dataset.path;
    let key = e.currentTarget.dataset.key;
    let bl = e.currentTarget.dataset.bl;
    setTimeout(function () {
      innerAudioContext.play();
    }.bind(that), 300)
    innerAudioContext.src = src;
    //切换显示状态
    for (var i = 0; i < that.data.lesson_res.length; i++) {
      that.data.lesson_res[i].bl = false;
    }
    that.data.lesson_res[key].bl = true;
    that.data.lesson_res[key].new = false;

    //开始监听
    innerAudioContext.onPlay(() => {
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })

    //结束监听
    innerAudioContext.onEnded(() => {
      that.data.lesson_res[key].bl = false;
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })
  },

  // 音频停止
  stoppAudio: function(e) {
    let that = this;
    let src = e.currentTarget.dataset.path;
    let key = e.currentTarget.dataset.key;
    let bl = e.currentTarget.dataset.bl;
    //切换显示状态
    for (let i = 0; i < that.data.lesson_res.length; i++) {
      that.data.lesson_res[i].bl = false;
    }
    that.data.lesson_res[key].bl = false;
    setTimeout(function () {
      innerAudioContext.stop();
    }.bind(that), 300)
    //停止监听
    innerAudioContext.onStop(() => {
      that.data.lesson_res[key].bl = false;
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })
    //结束监听
    innerAudioContext.onEnded(() => {
      that.data.lesson_res[key].bl = false;
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })
  },
  // 回到顶部
  goTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  // 使页面滚动到底部
  goBottom() {
    wx.createSelectorQuery().select('#discuss').boundingClientRect(function(rect) {
      wx.pageScrollTo({
        scrollTop: rect.bottom,
        duration: 600
      })
    }).exec()
  },
  //弹窗显示切换
  openTan(e) {
    let tan = e.currentTarget.dataset.tan
    if (!tan) {
      this.setData({
        showTan: true,
        showMessage: false, //评论
        showMenu: false, //切换菜单
        showMask: false //遮罩层
      })
    } else {
      this.setData({
        showTan: false,
        showMessage: false, //评论
        showMenu: false, //切换菜单
        showMask: false //遮罩层
      })
    }
  },
  //打开评论
  openMessage(e) {
    let tan = e.currentTarget.dataset.mes
    if (!tan) {
      this.setData({
        showMask: true,
        showMessage: true,
        showTan: false,
        showMenu: false
      })
    }
  },
  openMenu(e) {
    let tan = e.currentTarget.dataset.menu
    if (!tan) {
      this.setData({
        showMask: true,
        showMenu: true,
        showTan: false,
        showMessage: false
      })
    }
  },
  //评论赞赏弹窗切换
  commentTap(e) {
    console.log(e)
    let showComment = e.currentTarget.dataset.id
    if (showComment) {
      this.setData({
        showComment: showComment
      })
    } else {
      this.setData({
        showComment: showComment
      })
    }
  },
  //关闭评论
  closeMessage() {
    this.setData({
      showMask: false,
      showMessage: false
    })
  },
  closeMenu() {
    this.setData({
      showMask: false,
      showMenu: false
    })
  },
  closeAll() {
    this.setData({
      showMask: false,
      showMenu: false,
      showTan: false,
      showMessage: false
    })
  },
  showCommentInfo() {
    this.setData({
      commentShow: true
    })
  },
  closeComment() {
    this.setData({
      commentShow: false
    })
  },
  //声音控件start
  secondTransferTime: function(time) {
    if (time > 3600) {
      return [
          parseInt(time / 60 / 60),
          parseInt(time / 60 % 60),
          parseInt(time % 60)
        ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1");
    } else {
      return [
          parseInt(time / 60 % 60),
          parseInt(time % 60)
        ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1");
    }
  },
  // 点击slider时调用
  sliderTap: function(e) {
    console.log("sliderTap")
    this.seek()
  },

  // 开始滑动时
  sliderStart: function(e) {
    console.log("sliderStart")
  },

  // 正在滑动
  sliderChange: function(e) {
    console.log("sliderChange")
  },

  // 滑动结束
  sliderEnd: function(e) {
    console.log("sliderEnd")
    this.seek()
  },

  // 滑动取消 （左滑时滑到上一页面或电话等情况）
  sliderCancel: function(e) {
    console.log("sliderCancel")
    this.seek()
  },

  seek: function() {
    var value = this.wxzxSlider.properties.value
    console.log(value)
    var seek_time = value.toFixed(0);
    var pass_time = this.secondTransferTime(seek_time);
    this.setData({
      pass_time: pass_time,
    })
    audioManager.seek(Number(seek_time));
  },
  focus(e) {
    Toast('高度：' + e.detail.height,'noicon')
    if (this.data.isAndroid) {
      this.setData({
        andoridInput: true,
        andoridHeight: e.detail.height * 2
      })
    }
  },
  blur() {
    if (this.data.isAndroid) {
      this.setData({
        andoridInput: false
      })
    }
  },
  //声音控件end
  inputFocus() {
    if (this.data.isAndroid) {
      this.setData({
        androidInput: 1
      })
    } else {
      console.log('ios')
    }
  },
  inputBlur() {
    if (this.data.isAndroid) {
      this.setData({
        androidInput: 0
      })
    }
  },
  previewImg(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  },
  // 获取滚动条当前位置
  onPageScroll: function(e) {
    if (e.scrollTop > 200) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },

  //回到顶部
  goTop: function(e) { // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  onShareAppMessage: function(res) {
    let that = this
    return {
      title: that.data.lessoninfo.lesson_name,
      path: 'pages/voice/voice?id=' + that.data.lessonid,
      imageUrl: that.data.lessoninfo.lesson_img
    }
  },
  publishShow(){
    this.setData({
      showPublish: true
    });
  },
  closePublish(){
    this.setData({
      showPublish: false
    });
  }
})